package cn.wgspring.wedding_helper.settings

import cn.wgspring.wedding_helper.model.ShoppingItem
import cn.wgspring.wedding_helper.model.CheckListItem
import com.russhwolf.settings.Settings
import kotlinx.serialization.json.Json
import kotlinx.serialization.encodeToString

/**
 * 存储管理器，负责处理所有数据的本地持久化
 */
class StorageManager(private val settings: Settings) {
    companion object {
        // 存储键
        private const val SHOPPING_ITEMS_KEY = "shopping_items"
        private const val CHECK_ITEMS_KEY = "check_items"
        private const val SHOPPING_NEXT_ID_KEY = "shopping_next_id"
        private const val CHECK_NEXT_ID_KEY = "check_next_id"
        private const val TIME_PHASE_ORDER_KEY = "time_phase_order"
        private const val USER_GROUP_ORDER_KEY = "user_group_order"
        private const val CATEGORY_ORDER_MAP_KEY = "category_order_map"
        private const val SELECTED_TAB_KEY = "selected_tab"
        private const val TIME_PHASE_EXPANDED_PREFIX = "time_phase_expanded_"
        private const val USER_GROUP_EXPANDED_PREFIX = "user_group_expanded_"
        
        // 单例实例
        private var instance: StorageManager? = null
        
        fun getInstance(): StorageManager {
            if (instance == null) {
                instance = StorageManager(Settings())
            }
            return instance!!
        }
    }
    
    private val json = Json { 
        ignoreUnknownKeys = true 
        isLenient = true
    }
    
    // 获取下一个可用的购物项ID
    private fun getNextShoppingItemId(): Int {
        val nextId = settings.getIntOrNull(SHOPPING_NEXT_ID_KEY) ?: 1
        settings.putInt(SHOPPING_NEXT_ID_KEY, nextId + 1)
        return nextId
    }
    
    // 获取下一个可用的检查项ID
    private fun getNextCheckItemId(): Int {
        val nextId = settings.getIntOrNull(CHECK_NEXT_ID_KEY) ?: 1
        settings.putInt(CHECK_NEXT_ID_KEY, nextId + 1)
        return nextId
    }
    
    // 保存购物项列表
    fun saveShoppingItems(items: List<ShoppingItem>) {
        val jsonString = json.encodeToString(items)
        settings.putString(SHOPPING_ITEMS_KEY, jsonString)
    }
    
    // 获取所有购物项
    fun getShoppingItems(): List<ShoppingItem> {
        val jsonString = settings.getStringOrNull(SHOPPING_ITEMS_KEY) ?: return emptyList()
        return try {
            json.decodeFromString(jsonString)
        } catch (e: Exception) {
            emptyList()
        }
    }
    
    // 添加新的购物项，自动分配ID
    fun addShoppingItem(item: ShoppingItem): ShoppingItem {
        val newId = if (item.id <= 0) getNextShoppingItemId() else item.id
        val newItem = ShoppingItem(
            id = newId,
            name = item.name,
            category = item.category,
            timePhase = item.timePhase,
            quantity = item.quantity,
            note = item.note,
            purchased = item.purchased,
        )
        
        val items = getShoppingItems().toMutableList()
        items.add(newItem)
        saveShoppingItems(items)
        return newItem
    }
    
    // 更新购物项
    fun updateShoppingItem(item: ShoppingItem): ShoppingItem {
        val items = getShoppingItems().toMutableList()
        val index = items.indexOfFirst { it.id == item.id }
        
        if (index != -1) {
            items[index] = item
            saveShoppingItems(items)
            return item
        } else {
            return addShoppingItem(item)
        }
    }
    
    // 标记购物项为已删除
    fun markShoppingItemAsDeleted(id: Int) {
        val items = getShoppingItems().toMutableList()
        val index = items.indexOfFirst { it.id == id }
        
        if (index != -1) {
            val item = items[index]
            val updatedItem = ShoppingItem(
                id = item.id,
                name = item.name,
                category = item.category,
                timePhase = item.timePhase,
                quantity = item.quantity,
                note = item.note,
                purchased = item.isPurchased,
            )
            items[index] = updatedItem
            saveShoppingItems(items)
        }
    }
    
    // 保存检查项列表
    fun saveCheckItems(items: List<CheckListItem>) {
        val jsonString = json.encodeToString(items)
        settings.putString(CHECK_ITEMS_KEY, jsonString)
    }
    
    // 获取所有检查项
    fun getCheckItems(): List<CheckListItem> {
        val jsonString = settings.getStringOrNull(CHECK_ITEMS_KEY) ?: return emptyList()
        return try {
            json.decodeFromString(jsonString)
        } catch (e: Exception) {
            emptyList()
        }
    }
    
    // 添加新的检查项，自动分配ID
    fun addCheckItem(item: CheckListItem): CheckListItem {
        val newId = if (item.id <= 0) getNextCheckItemId() else item.id
        val newItem = CheckListItem(
            id = newId,
            name = item.name,
            userGroup = item.userGroup,
            purpose = item.purpose,
            location = item.location,
            confirmed = item.isConfirmed,
            userDefined = true,
            isDeleted = false
        )
        
        val items = getCheckItems().toMutableList()
        items.add(newItem)
        saveCheckItems(items)
        return newItem
    }
    
    // 更新检查项
    fun updateCheckItem(item: CheckListItem): CheckListItem {
        val items = getCheckItems().toMutableList()
        val index = items.indexOfFirst { it.id == item.id }
        
        if (index != -1) {
            items[index] = item
            saveCheckItems(items)
            return item
        } else {
            return addCheckItem(item)
        }
    }
    
    // 标记检查项为已删除
    fun markCheckItemAsDeleted(id: Int) {
        val items = getCheckItems().toMutableList()
        val index = items.indexOfFirst { it.id == id }
        
        if (index != -1) {
            val item = items[index]
            val updatedItem = CheckListItem(
                id = item.id,
                name = item.name,
                userGroup = item.userGroup,
                purpose = item.purpose,
                location = item.location,
                confirmed = item.isConfirmed,
                userDefined = item.userDefined,
                isDeleted = true
            )
            items[index] = updatedItem
            saveCheckItems(items)
        }
    }
    
    // 保存购物项的状态
    fun saveShoppingItemState(id: Int, purchased: Boolean) {
        val items = getShoppingItems().toMutableList()
        val index = items.indexOfFirst { it.id == id }
        
        if (index != -1) {
            val item = items[index]
            val updatedItem = ShoppingItem(
                id = item.id,
                name = item.name,
                category = item.category,
                timePhase = item.timePhase,
                quantity = item.quantity,
                note = item.note,
                purchased = purchased,
            )
            items[index] = updatedItem
            saveShoppingItems(items)
        }
    }
    
    // 保存检查项的状态
    fun saveCheckItemState(id: Int, confirmed: Boolean) {
        val items = getCheckItems().toMutableList()
        val index = items.indexOfFirst { it.id == id }
        
        if (index != -1) {
            val item = items[index]
            val updatedItem = CheckListItem(
                id = item.id,
                name = item.name,
                userGroup = item.userGroup,
                purpose = item.purpose,
                location = item.location,
                confirmed = confirmed,
                userDefined = item.userDefined,
                isDeleted = item.isDeleted
            )
            items[index] = updatedItem
            saveCheckItems(items)
        }
    }
    
    // 保存时间阶段顺序
    fun saveTimePhaseOrder(order: List<String>) {
        val jsonString = json.encodeToString(order)
        settings.putString(TIME_PHASE_ORDER_KEY, jsonString)
    }
    
    // 获取时间阶段顺序
    fun getTimePhaseOrder(): List<String> {
        val jsonString = settings.getStringOrNull(TIME_PHASE_ORDER_KEY) ?: return emptyList()
        return try {
            json.decodeFromString(jsonString)
        } catch (e: Exception) {
            emptyList()
        }
    }
    
    // 保存使用方顺序
    fun saveUserGroupOrder(order: List<String>) {
        val jsonString = json.encodeToString(order)
        settings.putString(USER_GROUP_ORDER_KEY, jsonString)
    }
    
    // 获取使用方顺序
    fun getUserGroupOrder(): List<String> {
        val jsonString = settings.getStringOrNull(USER_GROUP_ORDER_KEY) ?: return emptyList()
        return try {
            json.decodeFromString(jsonString)
        } catch (e: Exception) {
            emptyList()
        }
    }
    
    // 保存类别顺序映射
    fun saveCategoryOrderMap(map: Map<String, List<String>>) {
        val jsonString = json.encodeToString(map)
        settings.putString(CATEGORY_ORDER_MAP_KEY, jsonString)
    }
    
    // 获取类别顺序映射
    fun getCategoryOrderMap(): Map<String, List<String>> {
        val jsonString = settings.getStringOrNull(CATEGORY_ORDER_MAP_KEY) ?: return emptyMap()
        return try {
            json.decodeFromString(jsonString)
        } catch (e: Exception) {
            emptyMap()
        }
    }
    
    // 保存当前选中的Tab索引
    fun saveSelectedTab(tabIndex: Int) {
        settings.putInt(SELECTED_TAB_KEY, tabIndex)
    }
    
    // 获取保存的Tab索引，默认为0
    fun getSelectedTab(): Int {
        return settings.getIntOrNull(SELECTED_TAB_KEY) ?: 0
    }
    
    // 保存时间段的展开状态
    fun saveTimePhaseExpandedState(timePhase: String, expanded: Boolean) {
        val key = "$TIME_PHASE_EXPANDED_PREFIX$timePhase"
        settings.putBoolean(key, expanded)
    }
    
    // 获取时间段的展开状态，默认为展开
    fun getTimePhaseExpandedState(timePhase: String): Boolean {
        val key = "$TIME_PHASE_EXPANDED_PREFIX$timePhase"
        return settings.getBooleanOrNull(key) ?: true
    }
    
    // 保存使用方的展开状态
    fun saveUserGroupExpandedState(userGroup: String, expanded: Boolean) {
        val key = "$USER_GROUP_EXPANDED_PREFIX$userGroup"
        settings.putBoolean(key, expanded)
    }
    
    // 获取使用方的展开状态，默认为展开
    fun getUserGroupExpandedState(userGroup: String): Boolean {
        val key = "$USER_GROUP_EXPANDED_PREFIX$userGroup"
        return settings.getBooleanOrNull(key) ?: true
    }
} 